package com.example.HaiDLaobackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.HaiDLaobackend.common.ApiResponse;
import com.example.HaiDLaobackend.entity.CommentLikeEntity;
import com.example.HaiDLaobackend.entity.PostCommentEntity;
import com.example.HaiDLaobackend.entity.UserEntity;
import com.example.HaiDLaobackend.service.CommentLikeService;
import com.example.HaiDLaobackend.service.PostCommentService;
import com.example.HaiDLaobackend.service.PostService;
import com.example.HaiDLaobackend.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/posts/{postId}/comments")
public class PostCommentController {

	private final PostCommentService commentService;
	private final UserService userService;
	private final CommentLikeService commentLikeService;
	private final PostService postService;

	public PostCommentController(PostCommentService commentService, UserService userService,
			CommentLikeService commentLikeService, PostService postService) {
		this.commentService = commentService;
		this.userService = userService;
		this.commentLikeService = commentLikeService;
		this.postService = postService;
	}

	@GetMapping
	public ApiResponse<List<Map<String, Object>>> getComments(
			@PathVariable Long postId,
			HttpServletRequest request) {
		
		// 验证帖子存在
		if (postService.getById(postId) == null) {
			return ApiResponse.error("帖子不存在");
		}
		
		// 获取所有评论
		LambdaQueryWrapper<PostCommentEntity> qw = new LambdaQueryWrapper<>();
		qw.eq(PostCommentEntity::getPostId, postId)
			.orderByAsc(PostCommentEntity::getCreatedAt);
		
		List<PostCommentEntity> comments = commentService.list(qw);
		
		Long userId = (Long) request.getAttribute("currentUserId");
		
		// 构建树形结构
		List<Map<String, Object>> result = comments.stream()
			.filter(c -> c.getParentId() == null || c.getParentId() == 0)
			.map(parent -> buildCommentTree(parent, comments, userId))
			.collect(Collectors.toList());
		
		return ApiResponse.ok(result);
	}

	@PostMapping
	public ApiResponse<PostCommentEntity> createComment(
			@PathVariable Long postId,
			@RequestBody Map<String, Object> body,
			HttpServletRequest request) {
		
		Long userId = (Long) request.getAttribute("currentUserId");
		if (userId == null) {
			return ApiResponse.error("未登录");
		}
		
		// 验证帖子存在
		if (postService.getById(postId) == null) {
			return ApiResponse.error("帖子不存在");
		}
		
		// 违禁词审核
		String content = (String) body.get("content");
		if (content == null || content.trim().isEmpty()) {
			return ApiResponse.error("评论内容不能为空");
		}
		
		// 这里可以复用PostService的违禁词检查
		// 为了简化，暂时跳过
		
		UserEntity user = userService.getById(userId);
		if (user == null) {
			return ApiResponse.error("用户不存在");
		}
		
		PostCommentEntity comment = new PostCommentEntity();
		comment.setPostId(postId);
		comment.setUserId(userId);
		comment.setUserNickname(user.getNickname() != null ? user.getNickname() : user.getUsername());
		comment.setUserAvatarUrl(user.getAvatarUrl());
		comment.setContent(content);
		comment.setParentId(body.get("parentId") != null ? Long.valueOf(body.get("parentId").toString()) : 0L);
		comment.setLikeCount(0);
		comment.setCreatedAt(LocalDateTime.now());
		
		commentService.save(comment);
		
		return ApiResponse.ok(comment);
	}

	@PostMapping("/{commentId}/like")
	public ApiResponse<Map<String, Object>> toggleCommentLike(
			@PathVariable Long postId,
			@PathVariable Long commentId,
			HttpServletRequest request) {
		
		Long userId = (Long) request.getAttribute("currentUserId");
		if (userId == null) {
			return ApiResponse.error("未登录");
		}
		
		LambdaQueryWrapper<CommentLikeEntity> qw = new LambdaQueryWrapper<>();
		qw.eq(CommentLikeEntity::getCommentId, commentId)
			.eq(CommentLikeEntity::getUserId, userId);
		
		CommentLikeEntity existing = commentLikeService.getOne(qw);
		boolean isLiked;
		
		if (existing != null) {
			commentLikeService.removeById(existing.getId());
			isLiked = false;
		} else {
			CommentLikeEntity like = new CommentLikeEntity();
			like.setCommentId(commentId);
			like.setUserId(userId);
			like.setCreatedAt(LocalDateTime.now());
			commentLikeService.save(like);
			isLiked = true;
		}
		
		// 更新评论的点赞数
		long likeCount = commentLikeService.count(new LambdaQueryWrapper<CommentLikeEntity>()
			.eq(CommentLikeEntity::getCommentId, commentId));
		
		PostCommentEntity comment = commentService.getById(commentId);
		if (comment != null) {
			comment.setLikeCount((int) likeCount);
			commentService.updateById(comment);
		}
		
		Map<String, Object> result = new HashMap<>();
		result.put("isLiked", isLiked);
		result.put("likeCount", likeCount);
		
		return ApiResponse.ok(result);
	}

	private Map<String, Object> buildCommentTree(PostCommentEntity parent, 
			List<PostCommentEntity> allComments, Long currentUserId) {
		Map<String, Object> node = new HashMap<>();
		node.put("id", parent.getId());
		node.put("userId", parent.getUserId());
		node.put("userNickname", parent.getUserNickname());
		node.put("userAvatarUrl", parent.getUserAvatarUrl());
		node.put("content", parent.getContent());
		node.put("likeCount", parent.getLikeCount());
		node.put("createdAt", parent.getCreatedAt());
		
		// 检查当前用户是否已点赞
		boolean isLiked = false;
		if (currentUserId != null) {
			isLiked = commentLikeService.count(new LambdaQueryWrapper<CommentLikeEntity>()
				.eq(CommentLikeEntity::getCommentId, parent.getId())
				.eq(CommentLikeEntity::getUserId, currentUserId)) > 0;
		}
		node.put("isLiked", isLiked);
		
		// 获取子评论
		List<Map<String, Object>> children = allComments.stream()
			.filter(c -> c.getParentId() != null && c.getParentId().equals(parent.getId()))
			.map(child -> {
				Map<String, Object> childNode = new HashMap<>();
				childNode.put("id", child.getId());
				childNode.put("userId", child.getUserId());
				childNode.put("userNickname", child.getUserNickname());
				childNode.put("userAvatarUrl", child.getUserAvatarUrl());
				childNode.put("content", child.getContent());
				childNode.put("likeCount", child.getLikeCount());
				childNode.put("createdAt", child.getCreatedAt());
				
				boolean childLiked = false;
				if (currentUserId != null) {
					childLiked = commentLikeService.count(new LambdaQueryWrapper<CommentLikeEntity>()
						.eq(CommentLikeEntity::getCommentId, child.getId())
						.eq(CommentLikeEntity::getUserId, currentUserId)) > 0;
				}
				childNode.put("isLiked", childLiked);
				
				return childNode;
			})
			.collect(Collectors.toList());
		
		node.put("replies", children);
		
		return node;
	}
}

